package com.example.demo.service;

import com.example.demo.model.IoTData;
import com.example.demo.model.IoTDataDto;
import com.example.demo.repository.DailyMaxVoltage;
import com.example.demo.repository.IoTDataRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.HashMap;
import java.util.Map;

@Service
public class IoTDataService {
        @Autowired
    private IoTDataRepository ioTDataRepository;
    // --- 关键参数，您需要根据实际情况修改 ---
    private static final double THERMOCOUPLE_COEFFICIENT = 0.041; // 假设所有通道的零液流最小温差(ΔT_min)都是 0.01 (单位：毫伏或由您传感器决定)
    // 假设所有通道的零液流最大温差(ΔT_max)都是 0.8 (单位：毫伏或由您传感器决定)
  
    // 假设被测树木的边材面积是 0.005 平方米
    private static final double SAPWOOD_AREA_M2 = 0.005; 
    // 公式中的经验常数
    private static final double COEFF_A = 118.99;
    private static final double COEFF_B = 1.231;

    // 这个方法负责将原始的 IoTData 对象，转换为包含计算结果的 DTO 对象
    public IoTDataDto convertToDto(IoTData data) {
        IoTDataDto dto = new IoTDataDto();

        // 将原始数据的所有属性复制到DTO中
        // (因为IoTDataDto继承了IoTData, 我们需要手动复制)
        dto.setId(data.getId());
        dto.setJ1(data.getJ1()); // ...需要为所有35个字段都这样设置一遍...
        dto.setJ2(data.getJ2());
        dto.setJ3(data.getJ3());
        dto.setJ4(data.getJ4());
        dto.setJ5(data.getJ5());
        dto.setJ6(data.getJ6());
        dto.setJ7(data.getJ7());
        dto.setJ0(data.getJ0());
        dto.setT1(data.getT1());
        dto.setT2(data.getT2());
        dto.setT3(data.getT3());  
        dto.setT4(data.getT4());
        dto.setT5(data.getT5());
        dto.setT6(data.getT6());
        dto.setT7(data.getT7());
        dto.setT8(data.getT8());
        dto.setT9(data.getT9());
        dto.setT10(data.getT10());
        dto.setT11(data.getT11());
        dto.setT12(data.getT12());
        dto.setT13(data.getT13());
        dto.setT14(data.getT14());
        dto.setT15(data.getT15());
        dto.setT16(data.getT16());
        dto.setT17(data.getT17());
        dto.setT18(data.getT18());
        dto.setT19(data.getT19());
        dto.setT20(data.getT20());
        dto.setUid(data.getUid());
        dto.setUdt(data.getUdt());
        dto.setDid(data.getDid());
        dto.setNid(data.getNid());
        dto.setGpsx(data.getGpsx());
        dto.setGpsy(data.getGpsy());
        dto.setServerTimestamp(data.getServerTimestamp()); 
        // ... j3, j4 ... udt, did ... serverTimestamp 等等
        // (一个简化方法是使用 ModelMapper 或 MapStruct 库)

        // --- 开始计算液流速率 ---
        Map<String, Double> rates = new HashMap<>();
        // --- New, Efficient Calculation Logic ---
    
            String[] channels = {"j0", "j1", "j2", "j3", "j4", "j5", "j6", "j7"};
            String[] rawValues = {data.getJ0(), data.getJ1(), data.getJ2(), data.getJ3(), data.getJ4(), data.getJ5(), data.getJ6(), data.getJ7()};

            // Call our new repository method ONCE to get all max values for the day
            Optional<DailyMaxVoltage> dailyMaxesOpt = ioTDataRepository.findDailyMaxesForDate(data.getUdt());

            if (dailyMaxesOpt.isPresent()) {
                DailyMaxVoltage dailyMaxes = dailyMaxesOpt.get();
                // Create an array of the max voltage values for easy access in the loop
                Double[] maxVoltages = {
                    dailyMaxes.getMaxJ0(), dailyMaxes.getMaxJ1(), dailyMaxes.getMaxJ2(), dailyMaxes.getMaxJ3(),
                    dailyMaxes.getMaxJ4(), dailyMaxes.getMaxJ5(), dailyMaxes.getMaxJ6(), dailyMaxes.getMaxJ7()
                };

                for (int i = 0; i < channels.length; i++) {
                    // Get the specific max voltage for the current channel
                    Double d_v_max_mv = Optional.ofNullable(maxVoltages[i]).orElse(0.0);
                    double d_t_max = d_v_max_mv / THERMOCOUPLE_COEFFICIENT;
                    
                    String rawValue = rawValues[i];
                    double dV = 0.0;

                    if (rawValue != null && !rawValue.trim().isEmpty()) {
                        try {
                            dV = Double.parseDouble(rawValue);
                        } catch (NumberFormatException e) {
                            System.err.println("无法将 '" + rawValue + "' 转换为数字，通道为 " + channels[i]);
                            dV = 0.0;
                        }
                    }

                    double dT = dV / THERMOCOUPLE_COEFFICIENT;

                    if (d_t_max > 0 && dT > 0 && dT < d_t_max) {
                        double k = (d_t_max - dT) / dT;
                        double fs = COEFF_A * 3600 * SAPWOOD_AREA_M2 * Math.pow(k, COEFF_B);
                        rates.put(channels[i], fs);
                    } else {
                        rates.put(channels[i], 0.0);
                    }
                }
            } else {
                // If no max values found for that day, set all rates to 0
                for (String channel : channels) {
                    rates.put(channel, 0.0);
                }
            }
            
            dto.setSapFlowRates(rates);
        return dto;
    }
}